import Vue from 'vue'
import router from './router'
import store from './store'
import base from './config/baseUrl'

import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { notification } from 'ant-design-vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import Login from '@/views/user/Login'

let getWs = false
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['login', 'register', 'registerResult'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  var reg = new RegExp('token=([^&]*)(&|$)', 'i')
  var regUrl = new RegExp('baseURL=([^&]*)(&|$)', 'i')
  var arr = location.href.match(reg)
  var urlArr = location.href.match(regUrl)
  if (arr && arr[1]) {
    let token = arr && arr[1]
    if (!getWs) {
      if ('WebSocket' in window) {
        var ws = new WebSocket(process.env.VUE_APP_MODEL_BASE_WS + token) //创建WebSocket连接
        getWs = true
        ws.onerror = function (e) {
          //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
          console.log(e.error)
        }
        ws.onopen = function () {
          //当WebSocket创建成功时，触发onopen事件
          console.log('open')
        }
        ws.onmessage = function (e) {
          //当客户端收到服务端发来的消息时，触发onmessage事件，参数e.data包含server传递过来的数据
          console.log(e)
          if (e.data == 'logout') {
            //window.location.reload()
          }
        }
        ws.onclose = function (e) {
          //当客户端收到服务端发送的关闭连接请求时，触发onclose事件
          console.log('close')
        }
      } else {
        console.log('您的浏览器不支持WebSocket')
      }
    }
    sessionStorage.setItem('baseURL', urlArr[1])
    base.baseURL = urlArr[1]
    store.dispatch('SetToken', token).then(res => {
        if (store.getters.roles.length === 0) {
          store.dispatch('GetInfo')
            .then(() => {
              // 调用 vuex 的 从后端获取用户的路由菜单，动态添加可访问路由表
              store.dispatch('GenerateRoutes').then(() => {
                // 把已获取到的路由菜单加入到路由表中
                router.addRoutes(store.getters.addRouters)
                const redirect = decodeURIComponent(from.query.redirect || to.path)
                if (to.path === redirect) {
                  // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                  next({ path: to.path, replace: true })
                } else {
                  // 跳转到目的路由
                  next({ path: redirect })
                }
              })
            }).catch(
            (err) => {
              if (err.response.data.code == 401) {
                window.location.href = base.baseURL
              } else {
                notification.error({
                  message: '错误',
                  description: '请求用户信息失败，请重试',
                  duration: 3,
                })
                store.dispatch('Logout').then(() => {
                  setTimeout(() => {
                    window.location.href = base.baseURL
                  }, 2000)
                })
              }
            })
        } else {
          next()
        }
      }
    )
  } else if (Vue.ls.get(ACCESS_TOKEN)) {
    if (!getWs) {
      console.log(getWs)
      if ('WebSocket' in window) {
        var ws = new WebSocket(process.env.VUE_APP_MODEL_BASE_WS + Vue.ls.get(ACCESS_TOKEN)) //创建WebSocket连接
        getWs = true
        ws.onerror = function (e) {
          //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
          console.log(e.error)
        }
        ws.onopen = function () {
          //当WebSocket创建成功时，触发onopen事件
          console.log('open')
        }
        ws.onmessage = function (e) {
          //当客户端收到服务端发来的消息时，触发onmessage事件，参数e.data包含server传递过来的数据
          console.log(e)
          if (e.data == 'logout') {
            window.location.reload()
          }
        }
        ws.onclose = function (e) {
          //当客户端收到服务端发送的关闭连接请求时，触发onclose事件
          console.log('close')
        }
      } else {
        console.log('您的浏览器不支持WebSocket')
      }
    }
    if (store.getters.roles.length === 0) {
      store.dispatch('GetInfo')
        .then(() => {
          // 调用 vuex 的 从后端获取用户的路由菜单，动态添加可访问路由表
          store.dispatch('GenerateRoutes').then(() => {
            // 把已获取到的路由菜单加入到路由表中
            router.addRoutes(store.getters.addRouters)
            const redirect = decodeURIComponent(from.query.redirect || to.path)
            if (to.path === redirect) {
              // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
              next({ ...to, replace: true })
            } else {
              // 跳转到目的路由
              next({ path: redirect })
            }
          })
        })
        .catch((err) => {
          if (err.response.data.code == 401) {
            window.location.href = base.baseURL
          } else {
            notification.error({
              message: '错误',
              description: '请求用户信息失败，请重试',
              duration: 3,
            })
            store.dispatch('Logout').then(() => {
              setTimeout(() => {
                window.location.href = base.baseURL
              }, 2000)
            })
          }

        })
    } else {
      next()
    }
  } else {
   /* notification.error({
      message: '错误',
      description: '请求用户信息失败，请重试',
      duration: 3,
    })

    store.dispatch('Logout').then(() => {
      setTimeout(() => {

      }, 2000)
    })*/
    window.location.href = base.baseURL
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})

